/**
 * @file auth_service.cpp
 * @brief 认证服务主类实现 - 游戏微服务架构的认证服务核心
 * @author 29108
 * @date 2025/7/21
 * @version 1.0
 */

#include "core_services/auth_service/auth_service.h"
#include "common/logger/logger.h"
#include <sstream>
#include <algorithm>
#include <regex>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

namespace core_services {
    namespace auth_service {



        // ==================== GameLoginRequest 实现 ====================

        /**
         * @brief 从JSON创建游戏登录请求
         * @param json JSON对象
         * @return 游戏登录请求对象
         */
        GameLoginRequest GameLoginRequest::fromJson(const nlohmann::json& json) {
            GameLoginRequest request;

            if (json.contains("access_token")) request.access_token = json["access_token"];
            if (json.contains("game_type")) {
                if (json["game_type"].is_string()) {
                    request.game_type = stringToGameType(json["game_type"]);
                } else {
                    request.game_type = static_cast<GameType>(json["game_type"]);
                }
            }
            if (json.contains("preferred_server_region")) request.preferred_server_region = json["preferred_server_region"];
            if (json.contains("client_ip")) request.client_ip = json["client_ip"];
            if (json.contains("user_agent")) request.user_agent = json["user_agent"];
            if (json.contains("metadata")) request.metadata = json["metadata"];

            return request;
        }

        /**
         * @brief 转换为JSON对象
         * @return JSON对象
         */
        nlohmann::json GameLoginRequest::toJson() const {
            nlohmann::json json;

            json["access_token"] = access_token;
            json["game_type"] = gameTypeToString(game_type);
            json["preferred_server_region"] = preferred_server_region;
            json["client_ip"] = client_ip;
            json["user_agent"] = user_agent;
            json["metadata"] = metadata;

            return json;
        }

        /**
         * @brief 验证请求有效性
         * @return 验证结果，成功返回空字符串
         */
        std::string GameLoginRequest::validate() const {
            if (access_token.empty()) {
                return "访问令牌不能为空";
            }

            if (game_type == GameType::UNKNOWN) {
                return "游戏类型无效";
            }

            return ""; // 验证通过
        }

        // ==================== AuthService::Config 实现 ====================

        /**
         * @brief 从配置管理器加载配置
         * @return 认证服务配置对象
         */
        AuthService::Config AuthService::Config::fromConfigManager() {
            auto& config_manager = common::config::ConfigManager::getInstance();

            Config config;

            // 服务基础配置
            config.service_name = config_manager.get<std::string>("service.name", config.service_name);
            config.service_version = config_manager.get<std::string>("service.version", config.service_version);
            config.host = config_manager.get<std::string>("service.host", config.host);
            config.port = config_manager.get<int>("service.port", config.port);
            config.worker_threads = config_manager.get<int>("service.worker_threads", config.worker_threads);
            config.enable_https = config_manager.get<bool>("service.enable_https", config.enable_https);
            config.ssl_cert_file = config_manager.get<std::string>("service.ssl_cert_file", config.ssl_cert_file);
            config.ssl_key_file = config_manager.get<std::string>("service.ssl_key_file", config.ssl_key_file);

            // 数据库配置
            config.mysql_host = config_manager.get<std::string>("database.mysql.host", config.mysql_host);
            config.mysql_port = config_manager.get<int>("database.mysql.port", config.mysql_port);
            config.mysql_database = config_manager.get<std::string>("database.mysql.database", config.mysql_database);
            config.mysql_username = config_manager.get<std::string>("database.mysql.username", config.mysql_username);
            config.mysql_password = config_manager.get<std::string>("database.mysql.password", config.mysql_password);
            config.mysql_pool_size = config_manager.get<int>("database.mysql.pool_size", config.mysql_pool_size);

            config.redis_host = config_manager.get<std::string>("database.redis.host", config.redis_host);
            config.redis_port = config_manager.get<int>("database.redis.port", config.redis_port);
            config.redis_password = config_manager.get<std::string>("database.redis.password", config.redis_password);
            config.redis_database = config_manager.get<int>("database.redis.database", config.redis_database);
            config.redis_pool_size = config_manager.get<int>("database.redis.pool_size", config.redis_pool_size);

            // Kafka配置
            config.kafka_brokers = config_manager.get<std::string>("kafka.brokers", config.kafka_brokers);
            config.kafka_topic_prefix = config_manager.get<std::string>("kafka.topic_prefix", config.kafka_topic_prefix);
            config.enable_kafka = config_manager.get<bool>("kafka.enable", config.enable_kafka);

            // 服务发现配置
            config.enable_service_discovery = config_manager.get<bool>("service_discovery.enable", config.enable_service_discovery);
            config.api_gateway_host = config_manager.get<std::string>("service_discovery.api_gateway.host", config.api_gateway_host);
            config.api_gateway_port = config_manager.get<int>("service_discovery.api_gateway.port", config.api_gateway_port);
            config.heartbeat_interval = std::chrono::seconds(config_manager.get<int>("service_discovery.heartbeat_interval", config.heartbeat_interval.count()));

            // 性能配置
            config.max_concurrent_requests = config_manager.get<int>("performance.max_concurrent_requests", config.max_concurrent_requests);
            config.request_timeout = std::chrono::seconds(config_manager.get<int>("performance.request_timeout", config.request_timeout.count()));
            config.enable_request_logging = config_manager.get<bool>("performance.enable_request_logging", config.enable_request_logging);
            config.enable_metrics = config_manager.get<bool>("performance.enable_metrics", config.enable_metrics);

            return config;
        }

        /**
         * @brief 验证配置有效性
         * @return 验证结果，成功返回空字符串
         */
        std::string AuthService::Config::validate() const {
            if (service_name.empty()) {
                return "服务名称不能为空";
            }

            if (port <= 0 || port > 65535) {
                return "端口号必须在1-65535之间";
            }

            if (worker_threads <= 0) {
                return "工作线程数必须大于0";
            }

            if (mysql_host.empty()) {
                return "MySQL主机地址不能为空";
            }

            if (mysql_database.empty()) {
                return "MySQL数据库名不能为空";
            }

            if (redis_host.empty()) {
                return "Redis主机地址不能为空";
            }

            if (enable_kafka && kafka_brokers.empty()) {
                return "启用Kafka时代理地址不能为空";
            }

            if (enable_service_discovery && api_gateway_host.empty()) {
                return "启用服务发现时API Gateway主机地址不能为空";
            }

            return ""; // 验证通过
        }

        // ==================== AuthService 实现 ====================

        /**
         * @brief 构造函数
         * @param config 服务配置
         */
        AuthService::AuthService(const Config& config)
            : config_(config) {

            // 验证配置
            std::string validation_error = config_.validate();
            if (!validation_error.empty()) {
                throw std::invalid_argument("认证服务配置无效: " + validation_error);
            }

            LOG_INFO("认证服务创建完成");
            LOG_DEBUG("- 服务名称: " + config_.service_name);
            LOG_DEBUG("- 服务版本: " + config_.service_version);
            LOG_DEBUG("- 监听地址: " + config_.host + ":" + std::to_string(config_.port));
            LOG_DEBUG("- 工作线程数: " + std::to_string(config_.worker_threads));
        }

        /**
         * @brief 析构函数
         */
        AuthService::~AuthService() {
            try {
                if (running_) {
                    stop();
                }

                // 按照依赖关系的逆序安全重置智能指针
                // 1. 首先清理网络和业务组件
                http_server_.reset();

                // 2. 清理Kafka组件
                kafka_consumer_.reset();
                kafka_producer_.reset();

                // 3. 清理调度器和线程池
                if (scheduler_) {
                    scheduler_->stop();
                    LOG_INFO("任务调度器已停止");
                }
                scheduler_.reset();
                thread_pool_.reset();

                // 4. 清理业务组件（按依赖关系逆序）
                session_manager_.reset();
                jwt_manager_.reset();
                password_manager_.reset();
                user_repository_.reset();
                database_initializer_.reset();

                // 5. 最后清理数据库连接池
                mysql_pool_.reset();
                redis_pool_.reset();

                // 避免在析构时使用日志系统，使用标准输出
                std::cout << "[AuthService] 认证服务销毁完成" << std::endl;
            } catch (const std::exception& e) {
                // 析构函数中不应该抛出异常
                // 避免在析构时使用日志系统，使用标准错误输出
                std::cerr << "[AuthService] 认证服务析构时发生异常: " << e.what() << std::endl;
            } catch (...) {
                // 捕获所有其他异常，防止析构函数抛出
            }
        }

        /**
         * @brief 初始化服务
         * @return 初始化成功返回true
         */
        bool AuthService::initialize() {
            try {
                LOG_INFO("=== 认证服务初始化开始 ===");

                // 1. 初始化数据库连接池
                if (!initializeDatabasePools()) {
                    LOG_ERROR("数据库连接池初始化失败");
                    return false;
                }

                // 1.5. 初始化数据库表结构
                if (!initializeDatabaseSchema()) {
                    LOG_ERROR("数据库表结构初始化失败");
                    return false;
                }

                // 2. 初始化业务组件
                if (!initializeBusinessComponents()) {
                    LOG_ERROR("业务组件初始化失败");
                    return false;
                }

                // 3. 初始化HTTP服务器
                if (!initializeHttpServer()) {
                    LOG_ERROR("HTTP服务器初始化失败");
                    return false;
                }

                // 4. 初始化Kafka组件
                if (config_.enable_kafka) {
                    if (!initializeKafka()) {
                        LOG_ERROR("Kafka组件初始化失败");
                        return false;
                    }
                }

                // 5. 更新游戏服务器缓存
                updateGameServersCache();

                initialized_ = true;
                LOG_INFO("=== 认证服务初始化完成 ===");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("认证服务初始化时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 启动服务
         * @return 启动成功返回true
         */
        bool AuthService::start() {
            try {
                if (!initialized_) {
                    LOG_ERROR("服务未初始化，无法启动");
                    return false;
                }

                if (running_.load()) {
                    LOG_WARNING("服务已在运行中");
                    return true;
                }

                LOG_INFO("=== 认证服务启动开始 ===");

                // 1. 启动Kafka消费者
                if (config_.enable_kafka && kafka_consumer_) {
                    LOG_INFO("启动Kafka消费者...");
                    if (!startKafkaConsumer()) {
                        LOG_WARNING("Kafka消费者启动失败，但服务继续运行");
                    }
                }

                // 2. 注册到API Gateway
                if (config_.enable_service_discovery) {
                    LOG_INFO("注册到API Gateway...");
                    if (!registerToApiGateway()) {
                        LOG_WARNING("注册到API Gateway失败，但服务继续运行");
                    }
                }

                // 3. 启动定时任务
                LOG_INFO("启动定时任务...");
                startScheduledTasks();

                // 4. 启动心跳任务
                if (config_.enable_service_discovery) {
                    LOG_INFO("启动心跳任务...");
                    startHeartbeatTask();
                }

                // 5. 启动连接池监控
                LOG_INFO("启动连接池监控...");
                startConnectionPoolMonitoring();

                // 6. 设置运行状态
                running_.store(true);

                LOG_INFO("=== 认证服务组件启动完成 ===");
                LOG_INFO("准备启动HTTP服务器，地址: " + config_.host + ":" + std::to_string(config_.port));

                // 7. 最后启动HTTP服务器（这会阻塞主线程）
                LOG_INFO("启动HTTP服务器...");
                if (!startHttpServer()) {
                    LOG_ERROR("HTTP服务器启动失败");
                    return false;
                }

                // 注意：这里的代码在HTTP服务器停止后才会执行
                LOG_INFO("HTTP服务器已停止，认证服务退出");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("认证服务启动失败: " + std::string(e.what()));
                running_.store(false);

                // 清理已启动的组件
                cleanup();
                return false;
            }
        }

        /**
         * @brief 启动HTTP服务器（主线程版本）
         * @return 启动成功返回true
         */
        bool AuthService::startHttpServer() {
            try {
                if (!http_server_) {
                    LOG_ERROR("HTTP服务器未初始化");
                    return false;
                }

                // 简化端口检查（与API Gateway保持一致）
                LOG_INFO("准备绑定端口: " + config_.host + ":" + std::to_string(config_.port));

                LOG_INFO("=== 在主线程中启动HTTP服务器 ===");
                LOG_INFO("监听地址: " + config_.host + ":" + std::to_string(config_.port));
                LOG_INFO("工作线程数: " + std::to_string(config_.worker_threads));

                // 直接在主线程中启动HTTP服务器（类似API Gateway）
                bool start_result = http_server_->start();  // 这会阻塞主线程，直到服务停止

                if (start_result) {
                    LOG_INFO("HTTP服务器正常停止");
                } else {
                    LOG_ERROR("HTTP服务器启动失败");
                }

                return start_result;

            } catch (const std::exception& e) {
                LOG_ERROR("启动HTTP服务器失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 启动Kafka消费者
         * @return 启动成功返回true
         */
        bool AuthService::startKafkaConsumer() {
            try {
                if (!kafka_consumer_) {
                    LOG_WARNING("Kafka消费者未初始化");
                    return false;
                }

                // 订阅相关主题
                std::vector<std::string> topics = {
                    config_.kafka_topic_prefix + ".game_server.events",
                    config_.kafka_topic_prefix + ".user.events"
                };

                kafka_consumer_->subscribe(topics);

                // 启动消息处理
                kafka_consumer_->start([this](const std::string& topic, const std::string& key,
                                              const std::string& value, int64_t offset) {
                    (void)key;    // 消除未使用参数警告
                    (void)offset; // 消除未使用参数警告
                    this->handleKafkaMessage(topic, value);
                });

                LOG_INFO("Kafka消费者启动成功");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("启动Kafka消费者失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 清理资源
         */
        void AuthService::cleanup() {
            try {
                LOG_INFO("开始清理认证服务资源...");

                // 停止HTTP服务器
                if (http_server_) {
                    http_server_->stop();
                }

                // 停止Kafka消费者
                if (kafka_consumer_) {
                    kafka_consumer_->stop();
                }

                // 停止定时任务
                if (scheduler_) {
                    scheduler_->stop();
                }

                // 移除PID文件清理逻辑（改为依赖端口独占性）

                LOG_INFO("认证服务资源清理完成");

            } catch (const std::exception& e) {
                LOG_ERROR("清理资源时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 停止服务
         * @return 停止成功返回true
         */
        bool AuthService::stop() {
            try {
                if (!running_.load()) {
                    LOG_INFO("服务未运行，无需停止");
                    return true;
                }

                LOG_INFO("=== 认证服务停止开始 ===");

                // 设置总体超时时间，确保程序能在合理时间内退出
                auto stop_start_time = std::chrono::steady_clock::now();
                const auto max_stop_duration = std::chrono::seconds(10); // 最多等待10秒

                running_.store(false);

                // 1. 停止HTTP服务器（优雅关闭）
                if (http_server_) {
                    LOG_INFO("正在停止HTTP服务器，端口: " + std::to_string(config_.port));
                    try {
                        http_server_->stop();
                        LOG_INFO("HTTP服务器已停止，端口已释放");
                    } catch (const std::exception& e) {
                        LOG_ERROR("停止HTTP服务器时发生异常: " + std::string(e.what()));
                        // 继续执行其他清理操作
                    }
                }

                // HTTP服务器现在运行在主线程中，无需等待独立线程结束
                LOG_INFO("HTTP服务器已在主线程中停止");

                // 2. 停止Kafka组件
                if (kafka_consumer_) {
                    kafka_consumer_->stop();
                }

                // 3. 停止定时任务
                if (scheduler_) {
                    scheduler_->stop();
                }

                // 4. 停止连接池监控线程
                if (connection_pool_monitor_thread_.joinable()) {
                    LOG_INFO("等待连接池监控线程结束...");
                    try {
                        connection_pool_monitor_thread_.join();
                        LOG_INFO("连接池监控线程已结束");
                    } catch (const std::exception& e) {
                        LOG_ERROR("等待连接池监控线程结束时发生异常: " + std::string(e.what()));
                    }
                }

                // 5. 停止数据库连接池（带超时检查）
                auto current_time = std::chrono::steady_clock::now();
                if (current_time - stop_start_time < max_stop_duration && mysql_pool_) {
                    LOG_INFO("正在停止MySQL连接池...");
                    try {
                        mysql_pool_->stop();
                        LOG_INFO("MySQL连接池已停止");
                    } catch (const std::exception& e) {
                        LOG_ERROR("停止MySQL连接池时发生异常: " + std::string(e.what()));
                    }
                } else if (mysql_pool_) {
                    LOG_WARNING("停止超时，跳过MySQL连接池停止");
                }

                current_time = std::chrono::steady_clock::now();
                if (current_time - stop_start_time < max_stop_duration && redis_pool_) {
                    LOG_INFO("正在停止Redis连接池...");
                    try {
                        redis_pool_->stop();
                        LOG_INFO("Redis连接池已停止");
                    } catch (const std::exception& e) {
                        LOG_ERROR("停止Redis连接池时发生异常: " + std::string(e.what()));
                    }
                } else if (redis_pool_) {
                    LOG_WARNING("停止超时，跳过Redis连接池停止");
                }

                LOG_INFO("=== 认证服务停止完成 ===");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("认证服务停止时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        // ==================== 核心认证功能 ====================

        /**
         * @brief 用户注册
         * @param request 注册请求
         * @return 认证结果
         */
        AuthResult AuthService::registerUser(const AuthRequest& request) {
            try {
                total_requests_++;
                auto start_time = std::chrono::high_resolution_clock::now();

                // 1. 验证请求
                std::string validation_error = request.validate();
                if (!validation_error.empty()) {
                    failed_requests_++;
                    return AuthResult("请求验证失败: " + validation_error, "INVALID_REQUEST");
                }

                // 2. 检查用户是否已存在
                if (!request.username.empty()) {
                    auto existing_user = user_repository_->findUserByUsername(request.username);
                    if (existing_user.has_value()) {
                        failed_requests_++;
                        return AuthResult("用户名已存在", "USERNAME_EXISTS");
                    }
                }

                if (!request.email.empty()) {
                    auto existing_user = user_repository_->findUserByEmail(request.email);
                    if (existing_user.has_value()) {
                        failed_requests_++;
                        return AuthResult("邮箱已被注册", "EMAIL_EXISTS");
                    }
                }

                // 3. 验证密码强度
                auto password_validation = password_manager_->validatePasswordStrength(request.password, request.username, request.email);
                if (!password_validation.valid) {
                    failed_requests_++;
                    return AuthResult("密码不符合安全要求: " + password_validation.error_message, "WEAK_PASSWORD");
                }

                // 4. 哈希密码
                auto hash_result = password_manager_->hashPassword(request.password);
                if (!hash_result.success) {
                    failed_requests_++;
                    return AuthResult("密码处理失败: " + hash_result.error_message, "PASSWORD_HASH_FAILED");
                }

                // 5. 创建用户信息
                CoreUserInfo user_info;
                user_info.username = request.username;
                user_info.email = request.email;
                user_info.password_hash = hash_result.hash;
                user_info.salt = hash_result.salt;
                user_info.nickname = request.nickname.empty() ? request.username : request.nickname; // 使用请求中的昵称，如果为空则使用用户名
                user_info.status = UserStatus::ACTIVE;
                user_info.online_status = OnlineStatus::OFFLINE;
                user_info.roles = {"user"}; // 默认角色
                user_info.created_at = std::chrono::system_clock::now();
                user_info.updated_at = user_info.created_at;

                // 6. 保存到数据库
                int64_t user_id = user_repository_->createUser(user_info);
                if (user_id == 0) {
                    failed_requests_++;
                    return AuthResult("用户创建失败", "USER_CREATION_FAILED");
                }

                user_info.user_id = user_id;

                // 7. 创建会话
                auto session = session_manager_->createSession(user_info, request.client_ip, request.user_agent, request.device_id);
                if (!session.has_value()) {
                    failed_requests_++;
                    return AuthResult("会话创建失败", "SESSION_CREATION_FAILED");
                }

                // 8. 生成令牌
                std::string access_token = jwt_manager_->generateAccessToken(user_info, session->session_id, request.device_type, request.client_ip);
                std::string refresh_token = jwt_manager_->generateRefreshToken(user_info, session->session_id, request.device_type, request.client_ip);

                // 9. 发布用户注册事件
                publishUserEvent("user_registered", user_id, {
                    {"username", user_info.username},
                    {"email", user_info.email},
                    {"client_ip", request.client_ip},
                    {"device_type", request.device_type}
                });

                // 10. 记录统计信息
                registrations_++;
                successful_requests_++;

                auto end_time = std::chrono::high_resolution_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                // 11. 记录日志
                logRequest("/api/v1/auth/register", "POST", request.client_ip, user_id, 200, duration);

                LOG_INFO("用户注册成功，用户ID: " + std::to_string(user_id) + ", 用户名: " + user_info.username);

                return AuthResult(user_info, session.value(), access_token, refresh_token);

            } catch (const std::exception& e) {
                failed_requests_++;
                LOG_ERROR("用户注册时发生异常: " + std::string(e.what()));
                return AuthResult("服务器内部错误", "INTERNAL_ERROR");
            }
        }

        /**
         * @brief 用户登录
         * @param request 登录请求
         * @return 认证结果
         */
        AuthResult AuthService::loginUser(const AuthRequest& request) {
            try {
                total_requests_++;
                auto start_time = std::chrono::high_resolution_clock::now();

                // 1. 验证请求
                std::string validation_error = request.validate();
                if (!validation_error.empty()) {
                    failed_requests_++;
                    return AuthResult("请求验证失败: " + validation_error, "INVALID_REQUEST");
                }

                // 2. 查找用户
                LOG_INFO("开始查找用户，用户名: " + request.username);
                std::optional<CoreUserInfo> user_opt;

                // 增加重试机制，防止临时的连接池问题
                int max_user_query_retries = 2;
                for (int retry = 0; retry < max_user_query_retries; ++retry) {
                    try {
                        if (!request.username.empty()) {
                            user_opt = user_repository_->findUserByUsername(request.username);
                            LOG_INFO("用户名查找结果 (尝试 " + std::to_string(retry + 1) + "): " +
                                    std::string(user_opt.has_value() ? "找到用户" : "用户不存在"));
                        } else if (!request.email.empty()) {
                            user_opt = user_repository_->findUserByEmail(request.email);
                            LOG_INFO("邮箱查找结果 (尝试 " + std::to_string(retry + 1) + "): " +
                                    std::string(user_opt.has_value() ? "找到用户" : "用户不存在"));
                        }

                        // 如果查询成功（无论是否找到用户），跳出重试循环
                        break;

                    } catch (const std::exception& e) {
                        LOG_ERROR("查找用户时发生异常 (尝试 " + std::to_string(retry + 1) + "): " + std::string(e.what()));
                        if (retry < max_user_query_retries - 1) {
                            LOG_INFO("等待100ms后重试用户查询...");
                            std::this_thread::sleep_for(std::chrono::milliseconds(100));
                        } else {
                            failed_requests_++;
                            return AuthResult("用户查询服务暂时不可用", "SERVICE_UNAVAILABLE");
                        }
                    }
                }

                if (!user_opt.has_value()) {
                    failed_requests_++;
                    LOG_INFO("用户不存在: " + request.username);
                    return AuthResult("用户不存在", "USER_NOT_FOUND");
                }

                auto user_info = user_opt.value();

                // 3. 检查用户状态
                if (user_info.status == UserStatus::BANNED) {
                    failed_requests_++;
                    return AuthResult("用户已被封禁", "USER_BANNED");
                }

                if (user_info.status == UserStatus::SUSPENDED) {
                    failed_requests_++;
                    return AuthResult("用户已被暂停", "USER_SUSPENDED");
                }

                if (user_info.status == UserStatus::DELETED) {
                    failed_requests_++;
                    return AuthResult("用户已被删除", "USER_DELETED");
                }

                // 4. 检查账户锁定
                if (user_info.locked_until.has_value()) {
                    auto now = std::chrono::system_clock::now();
                    if (now < user_info.locked_until.value()) {
                        failed_requests_++;
                        return AuthResult("账户已被锁定", "ACCOUNT_LOCKED");
                    }
                }

                // 5. 验证密码（BCrypt不需要额外盐值）
                bool password_valid = password_manager_->verifyPassword(request.password, user_info.password_hash);
                if (!password_valid) {
                    // 增加登录失败次数
                    int new_login_attempts = user_info.login_attempts + 1;
                    std::optional<std::chrono::system_clock::time_point> new_locked_until = std::nullopt;

                    // 如果失败次数过多，锁定账户
                    if (new_login_attempts >= 5) {
                        new_locked_until = std::chrono::system_clock::now() + std::chrono::minutes(30);
                        LOG_WARNING("用户登录失败次数过多，账户已锁定，用户ID: " + std::to_string(user_info.user_id));
                    }

                    // 只更新登录相关信息，避免验证问题
                    user_repository_->updateUserLoginInfo(user_info.user_id, new_login_attempts,
                                                         new_locked_until, std::nullopt,
                                                         request.client_ip, user_info.online_status);

                    failed_requests_++;
                    return AuthResult("密码错误", "INVALID_PASSWORD");
                }

                // 6. 更新登录信息（重置失败次数，更新登录时间等）
                auto login_time = std::chrono::system_clock::now();
                user_repository_->updateUserLoginInfo(user_info.user_id, 0, std::nullopt,
                                                     login_time, request.client_ip, OnlineStatus::ONLINE);

                // 更新本地对象以便后续使用
                user_info.login_attempts = 0;
                user_info.locked_until = std::nullopt;
                user_info.last_login_at = login_time;
                user_info.last_login_ip = request.client_ip;
                user_info.online_status = OnlineStatus::ONLINE;

                // 9. 创建会话
                auto session = session_manager_->createSession(user_info, request.client_ip, request.user_agent, request.device_id);
                if (!session.has_value()) {
                    failed_requests_++;
                    return AuthResult("会话创建失败", "SESSION_CREATION_FAILED");
                }

                // 10. 生成令牌
                std::string access_token = jwt_manager_->generateAccessToken(user_info, session->session_id, request.device_type, request.client_ip);
                std::string refresh_token = jwt_manager_->generateRefreshToken(user_info, session->session_id, request.device_type, request.client_ip);

                // 11. 发布用户登录事件
                publishUserEvent("user_logged_in", user_info.user_id, {
                    {"username", user_info.username},
                    {"client_ip", request.client_ip},
                    {"device_type", request.device_type},
                    {"login_time", timePointToTimestamp(user_info.last_login_at.value())}
                });

                // 12. 记录统计信息
                logins_++;
                successful_requests_++;

                auto end_time = std::chrono::high_resolution_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                // 13. 记录日志
                logRequest("/api/v1/auth/login", "POST", request.client_ip, user_info.user_id, 200, duration);

                LOG_INFO("用户登录成功，用户ID: " + std::to_string(user_info.user_id) + ", 用户名: " + user_info.username);

                return AuthResult(user_info, session.value(), access_token, refresh_token);

            } catch (const std::exception& e) {
                failed_requests_++;
                LOG_ERROR("用户登录时发生异常: " + std::string(e.what()));
                return AuthResult("服务器内部错误", "INTERNAL_ERROR");
            }
        }

        /**
         * @brief 游戏登录
         * @param request 游戏登录请求
         * @return 游戏登录结果
         */
        GameLoginResult AuthService::gameLogin(const GameLoginRequest& request) {
            try {
                total_requests_++;
                auto start_time = std::chrono::high_resolution_clock::now();

                // 1. 验证请求
                std::string validation_error = request.validate();
                if (!validation_error.empty()) {
                    failed_requests_++;
                    return GameLoginResult("请求验证失败: " + validation_error, "INVALID_REQUEST");
                }

                // 2. 验证访问令牌
                auto token_validation = jwt_manager_->validateAccessToken(request.access_token);
                if (!token_validation.valid) {
                    failed_requests_++;
                    return GameLoginResult("令牌验证失败: " + token_validation.error_message, "INVALID_TOKEN");
                }

                auto user_claims = token_validation.claims.value();

                // 3. 获取用户信息
                auto user_opt = user_repository_->findUserById(user_claims.user_id);
                if (!user_opt.has_value()) {
                    failed_requests_++;
                    return GameLoginResult("用户不存在", "USER_NOT_FOUND");
                }

                auto user_info = user_opt.value();

                // 4. 检查用户状态
                if (user_info.status != UserStatus::ACTIVE) {
                    failed_requests_++;
                    return GameLoginResult("用户状态异常", "USER_STATUS_INVALID");
                }

                // 5. 获取或创建游戏用户数据
                auto game_data_opt = user_repository_->getUserGameData(user_info.user_id, request.game_type);
                GameUserData game_data;

                if (game_data_opt.has_value()) {
                    game_data = game_data_opt.value();
                } else {
                    // 创建新的游戏用户数据
                    game_data.user_id = user_info.user_id;
                    game_data.game_type = request.game_type;
                    game_data.level = 1;
                    game_data.experience = 0;
                    game_data.coins = 1000; // 初始金币
                    game_data.gems = 10;    // 初始宝石
                    game_data.created_at = std::chrono::system_clock::now();
                    game_data.updated_at = game_data.created_at;

                    // 保存到数据库
                    if (!user_repository_->createGameUserData(game_data)) {
                        LOG_WARNING("创建游戏用户数据失败，用户ID: " + std::to_string(user_info.user_id));
                    }
                }

                // 6. 选择最佳游戏服务器
                auto server_opt = selectBestGameServer(request.game_type, request.preferred_server_region);
                if (!server_opt.has_value()) {
                    failed_requests_++;
                    return GameLoginResult("没有可用的游戏服务器", "NO_AVAILABLE_SERVER");
                }

                auto server_info = server_opt.value();

                // 7. 生成游戏会话令牌
                std::string game_session_token = jwt_manager_->generateGameSessionToken(user_info, request.game_type, server_info.server_id);

                // 8. 创建游戏登录结果
                GameLoginResult result(request.game_type, game_data, server_info.host, server_info.port);
                result.game_server_id = server_info.server_id;
                result.game_session_token = game_session_token;

                // 9. 发布游戏登录事件
                publishGameEvent("game_login", user_info.user_id, request.game_type, {
                    {"server_id", server_info.server_id},
                    {"server_host", server_info.host},
                    {"server_port", server_info.port},
                    {"client_ip", request.client_ip},
                    {"login_time", getCurrentTimestamp()}
                });

                // 10. 记录统计信息
                game_logins_++;
                successful_requests_++;

                auto end_time = std::chrono::high_resolution_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                // 11. 记录日志
                logRequest("/api/v1/game/login", "POST", request.client_ip, user_info.user_id, 200, duration);

                LOG_INFO("游戏登录成功，用户ID: " + std::to_string(user_info.user_id) +
                        ", 游戏类型: " + gameTypeToString(request.game_type) +
                        ", 服务器: " + server_info.server_id);

                return result;

            } catch (const std::exception& e) {
                failed_requests_++;
                LOG_ERROR("游戏登录时发生异常: " + std::string(e.what()));
                return GameLoginResult("服务器内部错误", "INTERNAL_ERROR");
            }
        }

        /**
         * @brief 选择最佳游戏服务器
         * @param game_type 游戏类型
         * @param user_location 用户位置（可选）
         * @return 最佳游戏服务器信息，未找到返回nullopt
         */
        std::optional<GameServerInfo> AuthService::selectBestGameServer(GameType game_type, const std::string& user_location) {
            try {
                std::shared_lock<std::shared_mutex> lock(game_servers_mutex_);

                auto it = game_servers_cache_.find(game_type);
                if (it == game_servers_cache_.end() || it->second.empty()) {
                    LOG_WARNING("没有找到游戏类型的服务器: " + gameTypeToString(game_type));
                    return std::nullopt;
                }

                auto& servers = it->second;

                // 过滤可用的服务器
                std::vector<GameServerInfo> available_servers;
                for (const auto& server : servers) {
                    if (server.isAvailable()) {
                        available_servers.push_back(server);
                    }
                }

                if (available_servers.empty()) {
                    LOG_WARNING("没有可用的游戏服务器，游戏类型: " + gameTypeToString(game_type));
                    return std::nullopt;
                }

                // 如果指定了区域偏好，优先选择该区域的服务器
                if (!user_location.empty()) {
                    for (const auto& server : available_servers) {
                        if (server.metadata.find("region") != server.metadata.end() &&
                            server.metadata.at("region") == user_location) {
                            return server;
                        }
                    }
                }

                // 根据服务器评分选择最佳服务器
                auto best_server = std::max_element(available_servers.begin(), available_servers.end(),
                    [](const GameServerInfo& a, const GameServerInfo& b) {
                        return a.calculateScore() < b.calculateScore();
                    });

                return *best_server;

            } catch (const std::exception& e) {
                LOG_ERROR("选择最佳游戏服务器时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        // ==================== HTTP路由注册 ====================

        /**
         * @brief 注册HTTP路由
         */
        void AuthService::registerHttpRoutes() {
            if (!http_server_) {
                LOG_ERROR("HTTP服务器未初始化");
                return;
            }

            // ==================== 认证相关路由 ====================

            // 用户注册
            http_server_->route("POST", "/api/v1/auth/register",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    try {
                        std::string request_body = req.getBody();
                        if (request_body.empty()) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("EMPTY_REQUEST_BODY", "请求体不能为空").dump());
                            return;
                        }

                        // 检查Content-Type
                        std::string content_type = req.getHeader("Content-Type");
                        if (content_type.find("application/json") == std::string::npos) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("INVALID_CONTENT_TYPE", "Content-Type必须为application/json").dump());
                            return;
                        }

                        // 解析JSON请求体
                        nlohmann::json json_body;
                        try {
                            json_body = nlohmann::json::parse(request_body);
                        } catch (const nlohmann::json::parse_error& e) {
                            LOG_ERROR("JSON解析失败: " + std::string(e.what()));
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("INVALID_JSON", "请求体JSON格式无效").dump());
                            return;
                        }

                        auto auth_request = AuthRequest::fromJson(json_body);
                        auth_request.client_ip = req.getClientIP();
                        auth_request.user_agent = req.getHeader("User-Agent");

                        auto result = this->registerUser(auth_request);

                        if (result.success) {
                            res.setStatus(200);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildSuccessResponse(result.toJson()).dump());
                        } else {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse(result.error_code, result.message).dump());
                        }
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理注册请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 用户登录
            http_server_->route("POST", "/api/v1/auth/login",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    LOG_INFO("=== 认证服务收到登录请求 ===");
                    LOG_INFO("来源IP: " + req.getClientIP());
                    LOG_INFO("请求路径: " + req.getPath());
                    LOG_INFO("请求方法: " + req.getMethodString());
                    LOG_INFO("请求体长度: " + std::to_string(req.getBody().length()));
                    LOG_INFO("Content-Type: " + req.getHeader("Content-Type"));
                    try {
                        std::string request_body = req.getBody();
                        if (request_body.empty()) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("EMPTY_REQUEST_BODY", "请求体不能为空").dump());
                            return;
                        }

                        // 检查Content-Type
                        std::string content_type = req.getHeader("Content-Type");
                        if (content_type.find("application/json") == std::string::npos) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("INVALID_CONTENT_TYPE", "Content-Type必须为application/json").dump());
                            return;
                        }

                        // 解析JSON请求体
                        nlohmann::json json_body;
                        try {
                            json_body = nlohmann::json::parse(request_body);
                        } catch (const nlohmann::json::parse_error& e) {
                            LOG_ERROR("JSON解析失败: " + std::string(e.what()));
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("INVALID_JSON", "请求体JSON格式无效").dump());
                            return;
                        }

                        auto auth_request = AuthRequest::fromJson(json_body);
                        auth_request.client_ip = req.getClientIP();
                        auth_request.user_agent = req.getHeader("User-Agent");

                        LOG_DEBUG("处理登录请求，用户名: " + auth_request.username + ", 设备类型: " + auth_request.device_type);
                        auto result = this->loginUser(auth_request);

                        if (result.success) {
                            res.setStatus(200);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildSuccessResponse(result.toJson()).dump());
                        } else {
                            res.setStatus(401);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse(result.error_code, result.message).dump());
                        }
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理登录请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 用户登出
            http_server_->route("POST", "/api/v1/auth/logout",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    try {
                        std::string access_token;
                        std::string auth_header = req.getHeader("Authorization");
                        if (!auth_header.empty() && auth_header.substr(0, 7) == "Bearer ") {
                            access_token = auth_header.substr(7);
                        }

                        if (access_token.empty()) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("MISSING_TOKEN", "缺少访问令牌").dump());
                            return;
                        }

                        bool success = this->logoutUser(access_token);

                        if (success) {
                            res.setStatus(200);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildSuccessResponse({{"message", "登出成功"}}).dump());
                        } else {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("LOGOUT_FAILED", "登出失败").dump());
                        }
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理登出请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 刷新令牌
            http_server_->route("POST", "/api/v1/auth/refresh",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    try {
                        auto json_body = nlohmann::json::parse(req.getBody());
                        if (!json_body.contains("refresh_token")) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("MISSING_REFRESH_TOKEN", "缺少刷新令牌").dump());
                            return;
                        }

                        std::string refresh_token = json_body["refresh_token"];
                        auto result = this->refreshToken(refresh_token);

                        if (result.success) {
                            res.setStatus(200);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildSuccessResponse(result.toJson()).dump());
                        } else {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse(result.error_code, result.message).dump());
                        }
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理刷新令牌请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 验证令牌
            http_server_->route("GET", "/api/v1/auth/validate",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    try {
                        std::string access_token;
                        std::string auth_header = req.getHeader("Authorization");
                        if (!auth_header.empty() && auth_header.substr(0, 7) == "Bearer ") {
                            access_token = auth_header.substr(7);
                        }

                        if (access_token.empty()) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("MISSING_TOKEN", "缺少访问令牌").dump());
                            return;
                        }

                        auto result = this->validateToken(access_token, req.getClientIP());

                        if (result.valid) {
                            res.setStatus(200);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildSuccessResponse(result.toJson()).dump());
                        } else {
                            res.setStatus(401);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse(result.error_code, result.error_message).dump());
                        }
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理令牌验证请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // ==================== 游戏相关路由 ====================

            // 游戏登录
            http_server_->route("POST", "/api/v1/game/login",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    try {
                        GameLoginRequest game_request;

                        // 处理请求体
                        std::string request_body = req.getBody();
                        if (!request_body.empty()) {
                            // 如果有请求体，解析JSON
                            game_request = GameLoginRequest::fromJson(nlohmann::json::parse(request_body));
                        } else {
                            // 如果没有请求体，使用默认值
                            game_request.game_type = GameType::SNAKE; // 默认游戏类型
                            game_request.preferred_server_region = "default"; // 默认区域
                        }

                        // 从Authorization头获取access_token（如果请求体中没有）
                        if (game_request.access_token.empty()) {
                            std::string auth_header = req.getHeader("Authorization");
                            if (auth_header.length() >= 7 && auth_header.substr(0, 7) == "Bearer ") {
                                game_request.access_token = auth_header.substr(7);
                            }
                        }

                        game_request.client_ip = req.getClientIP();
                        game_request.user_agent = req.getHeader("User-Agent");

                        auto result = this->gameLogin(game_request);

                        if (result.success) {
                            res.setStatus(200);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildSuccessResponse(result.toJson()).dump());
                        } else {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse(result.error_code, result.message).dump());
                        }
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理游戏登录请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 获取游戏服务器列表
            http_server_->route("GET", "/api/v1/game/servers",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    try {
                        std::string game_type_str = req.getQueryParam("game_type");
                        std::string region = req.getQueryParam("region");

                        if (game_type_str.empty()) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("MISSING_GAME_TYPE", "缺少游戏类型参数").dump());
                            return;
                        }

                        GameType game_type = stringToGameType(game_type_str);
                        if (game_type == GameType::UNKNOWN) {
                            res.setStatus(400);
                            res.setHeader("Content-Type", "application/json");
                            res.setBody(buildErrorResponse("INVALID_GAME_TYPE", "无效的游戏类型").dump());
                            return;
                        }

                        auto servers = this->getGameServers(game_type, region);

                        nlohmann::json servers_json = nlohmann::json::array();
                        for (const auto& server : servers) {
                            servers_json.push_back(server.toJson());
                        }

                        res.setStatus(200);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildSuccessResponse({{"servers", servers_json}}).dump());
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理获取游戏服务器请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // ==================== 健康检查和管理路由 ====================

            // 健康检查
            http_server_->route("GET", "/health",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    (void)req; // 消除未使用参数警告
                    try {
                        auto health_status = this->getHealthCheck();
                        res.setStatus(200);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(health_status.dump());
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理健康检查请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 服务状态
            http_server_->route("GET", "/api/v1/admin/status",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    (void)req; // 消除未使用参数警告
                    try {
                        auto status = this->getServiceStatus();
                        res.setStatus(200);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(status.dump());
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理服务状态请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });

            // 统计信息
            http_server_->route("GET", "/api/v1/admin/statistics",
                [this](const common::http::HttpRequest& req, common::http::HttpResponse& res) {
                    (void)req; // 消除未使用参数警告
                    try {
                        auto statistics = this->getServiceStatistics();
                        res.setStatus(200);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(statistics.dump());
                    } catch (const std::exception& e) {
                        LOG_ERROR("处理统计信息请求时发生异常: " + std::string(e.what()));
                        res.setStatus(500);
                        res.setHeader("Content-Type", "application/json");
                        res.setBody(buildErrorResponse("INTERNAL_ERROR", "服务器内部错误").dump());
                    }
                });


        }

        // ==================== Kafka事件处理 ====================

        /**
         * @brief 处理Kafka消息
         * @param topic 主题
         * @param message 消息
         */
        void AuthService::handleKafkaMessage(const std::string& topic, const std::string& message) {
            try {
                auto event = nlohmann::json::parse(message);
                std::string event_type = event.contains("event_type") ? event["event_type"] : "";

                LOG_DEBUG("收到Kafka消息，主题: " + topic + ", 事件类型: " + event_type);

                // 处理游戏服务器事件
                if (topic.find("game_server.events") != std::string::npos) {
                    if (event_type == "server_status_update") {
                        handleGameServerStatusUpdate(GameServerInfo::fromJson(event["data"]));
                    } else if (event_type == "server_registered") {
                        handleGameServerRegistered(GameServerInfo::fromJson(event["data"]));
                    } else if (event_type == "server_unregistered") {
                        handleGameServerUnregistered(event["data"]["server_id"]);
                    }
                }
                // 处理用户事件
                else if (topic.find("user.events") != std::string::npos) {
                    if (event_type == "user_banned") {
                        handleUserBanned(event["user_id"]);
                    } else if (event_type == "user_unbanned") {
                        handleUserUnbanned(event["user_id"]);
                    }
                }
                // 处理管理员事件
                else if (topic.find("admin.events") != std::string::npos) {
                    if (event_type == "force_logout") {
                        handleForceLogout(event["user_id"]);
                    } else if (event_type == "clear_cache") {
                        handleClearCache(event["cache_type"]);
                    }
                }

            } catch (const std::exception& e) {
                LOG_ERROR("处理Kafka消息时发生异常: " + std::string(e.what()) + ", 主题: " + topic);
            }
        }

        /**
         * @brief 处理游戏服务器状态更新
         * @param server_info 服务器信息
         * @return 处理成功返回true
         */
        bool AuthService::handleGameServerStatusUpdate(const GameServerInfo& server_info) {
            try {
                std::unique_lock<std::shared_mutex> lock(game_servers_mutex_);

                // 更新游戏服务器缓存
                auto& servers = game_servers_cache_[server_info.game_type];
                auto it = std::find_if(servers.begin(), servers.end(),
                    [&](const GameServerInfo& s) { return s.server_id == server_info.server_id; });

                if (it != servers.end()) {
                    *it = server_info;
                    LOG_DEBUG("更新游戏服务器状态: " + server_info.server_id);
                } else {
                    servers.push_back(server_info);
                    LOG_DEBUG("添加新游戏服务器: " + server_info.server_id);
                }

                last_server_update_ = std::chrono::system_clock::now();
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("处理游戏服务器状态更新时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        // ==================== 事件发布 ====================

        /**
         * @brief 发布用户事件
         * @param event_type 事件类型
         * @param user_id 用户ID
         * @param event_data 事件数据
         * @return 发布成功返回true
         */
        bool AuthService::publishUserEvent(const std::string& event_type, int64_t user_id, const nlohmann::json& event_data) {
            try {
                if (!config_.enable_kafka || !kafka_producer_) {
                    return false;
                }

                nlohmann::json event = {
                    {"event_type", event_type},
                    {"service", config_.service_name},
                    {"service_version", config_.service_version},
                    {"user_id", user_id},
                    {"timestamp", getCurrentTimestamp()},
                    {"data", event_data}
                };

                std::string topic = config_.kafka_topic_prefix + ".user.events";
                std::string key = std::to_string(user_id);
                bool success = kafka_producer_->send(topic, key, event.dump());

                if (success) {
                    LOG_DEBUG("用户事件发布成功，类型: " + event_type + ", 用户ID: " + std::to_string(user_id));
                } else {
                    LOG_WARNING("用户事件发布失败，类型: " + event_type + ", 用户ID: " + std::to_string(user_id));
                }

                return success;

            } catch (const std::exception& e) {
                LOG_ERROR("发布用户事件时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 发布游戏事件
         * @param event_type 事件类型
         * @param user_id 用户ID
         * @param game_type 游戏类型
         * @param event_data 事件数据
         * @return 发布成功返回true
         */
        bool AuthService::publishGameEvent(const std::string& event_type, int64_t user_id, GameType game_type, const nlohmann::json& event_data) {
            try {
                if (!config_.enable_kafka || !kafka_producer_) {
                    return false;
                }

                nlohmann::json event = {
                    {"event_type", event_type},
                    {"service", config_.service_name},
                    {"service_version", config_.service_version},
                    {"user_id", user_id},
                    {"game_type", gameTypeToString(game_type)},
                    {"timestamp", getCurrentTimestamp()},
                    {"data", event_data}
                };

                std::string topic = config_.kafka_topic_prefix + ".game.events";
                std::string key = std::to_string(user_id) + "_" + std::to_string(static_cast<int>(game_type));
                bool success = kafka_producer_->send(topic, key, event.dump());

                if (success) {
                    LOG_DEBUG("游戏事件发布成功，类型: " + event_type + ", 用户ID: " + std::to_string(user_id));
                } else {
                    LOG_WARNING("游戏事件发布失败，类型: " + event_type + ", 用户ID: " + std::to_string(user_id));
                }

                return success;

            } catch (const std::exception& e) {
                LOG_ERROR("发布游戏事件时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        // ==================== 内部方法实现 ====================

        /**
         * @brief 初始化数据库连接池
         * @return 初始化成功返回true
         */
        bool AuthService::initializeDatabasePools() {
            try {
                // 初始化MySQL连接池
                common::database::MySQLPool::mysqlConfig mysql_config;
                mysql_config.host = config_.mysql_host;
                mysql_config.port = config_.mysql_port;
                mysql_config.database = config_.mysql_database;
                mysql_config.user = config_.mysql_username;
                mysql_config.password = config_.mysql_password;
                mysql_config.max_size = config_.mysql_pool_size;
                mysql_config.initial_size = std::min(20, config_.mysql_pool_size); // 设置初始连接数
                mysql_config.min_size = 10; // 设置最小连接数

                // 优化连接超时参数，提高响应速度
                mysql_config.connect_timeout = 5;  // 5秒连接超时（减少等待时间）
                mysql_config.read_timeout = 15;    // 15秒读取超时（减少等待时间）
                mysql_config.write_timeout = 15;   // 15秒写入超时（减少等待时间）

                // 优化连接池参数
                mysql_config.idle_timeout = std::chrono::minutes(5);  // 5分钟空闲超时（减少资源占用）
                mysql_config.health_check_interval = std::chrono::seconds(15); // 15秒健康检查（更频繁的检查）

                mysql_pool_ = std::make_shared<common::database::MySQLPool>(mysql_config);
                mysql_pool_->start();
                if (!mysql_pool_->isRunning()) {
                    LOG_ERROR("MySQL连接池启动失败");
                    return false;
                }

                // 初始化Redis连接池
                common::database::RedisPool::redisConfig redis_config;
                redis_config.host = config_.redis_host;
                redis_config.port = config_.redis_port;
                redis_config.password = config_.redis_password;
                redis_config.database = config_.redis_database;
                redis_config.max_size = config_.redis_pool_size;

                redis_pool_ = std::make_shared<common::database::RedisPool>(redis_config);
                redis_pool_->start();
                if (!redis_pool_->isRunning()) {
                    LOG_ERROR("Redis连接池启动失败");
                    return false;
                }

                LOG_INFO("数据库连接池初始化完成");

                // 注意：连接池监控将在服务启动时统一启动
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("初始化数据库连接池时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 初始化数据库表结构
         * @return 初始化成功返回true
         */
        bool AuthService::initializeDatabaseSchema() {
            try {
                LOG_INFO("开始初始化数据库表结构");

                // 检查连接池状态
                if (!mysql_pool_ || !mysql_pool_->isRunning()) {
                    LOG_ERROR("MySQL连接池未运行，无法初始化数据库表结构");
                    return false;
                }

                // 创建数据库初始化器
                database_initializer_ = std::make_unique<DatabaseInitializer>(mysql_pool_);

                // 检查是否所有必需表都存在
                LOG_DEBUG("检查必需表是否存在...");
                if (database_initializer_->checkAllRequiredTablesExist()) {
                    LOG_INFO("所有必需的数据库表都已存在");
                    return true;
                }

                // 获取缺失的表列表
                auto missing_tables = database_initializer_->getMissingTables();
                if (!missing_tables.empty()) {
                    LOG_INFO("发现缺失的数据库表，开始自动创建");
                    for (const auto& table : missing_tables) {
                        LOG_DEBUG("缺失表: " + table);
                    }

                    // 初始化数据库
                    auto result = database_initializer_->initializeDatabase(false);

                    if (result.success) {
                        LOG_INFO("数据库表结构初始化成功");
                        LOG_DEBUG("创建表数量: " + std::to_string(result.created_tables.size()));
                        LOG_DEBUG("现有表数量: " + std::to_string(result.existing_tables.size()));
                        LOG_DEBUG("执行时间: " + std::to_string(result.execution_time.count()) + "ms");

                        for (const auto& table : result.created_tables) {
                            LOG_DEBUG("已创建表: " + table);
                        }
                    } else {
                        LOG_ERROR("数据库表结构初始化失败");
                        for (const auto& error : result.errors) {
                            LOG_ERROR("初始化错误: " + error);
                        }
                        return false;
                    }
                }

                LOG_INFO("数据库表结构初始化完成");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("初始化数据库表结构时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 初始化业务组件
         * @return 初始化成功返回true
         */
        bool AuthService::initializeBusinessComponents() {
            try {
                // 初始化线程池
                common::thread_pool::ThreadPool::Config thread_config;
                thread_config.core_pool_size = config_.worker_threads;
                thread_config.maximum_pool_size = config_.worker_threads * 2;
                thread_config.queue_capacity = 1000;
                thread_config.rejection_policy = "caller_runs";
                thread_pool_ = std::make_shared<common::thread_pool::ThreadPool>(thread_config);

                // 初始化调度器
                common::scheduler::TaskScheduler::Config scheduler_config;
                scheduler_config.worker_threads = 4;
                scheduler_config.max_pending_tasks = 1000;
                scheduler_ = std::make_shared<common::scheduler::TaskScheduler>(scheduler_config);

                // 启动调度器
                scheduler_->start();
                LOG_INFO("任务调度器启动成功");

                // 初始化JWT管理器
                auto jwt_config = JwtManager::Config::fromConfigManager();
                jwt_manager_ = std::make_unique<JwtManager>(jwt_config, redis_pool_);

                // 初始化密码管理器
                auto password_config = PasswordManager::Config::fromConfigManager();
                password_manager_ = std::make_unique<PasswordManager>(password_config);

                // 初始化会话管理器
                auto session_config = SessionManager::Config::fromConfigManager();
                session_manager_ = std::make_unique<SessionManager>(session_config, redis_pool_,
                    std::shared_ptr<JwtManager>(jwt_manager_.get(), [](JwtManager*){}), thread_pool_);

                // 初始化用户数据访问层
                auto repository_config = UserRepository::Config::fromConfigManager();
                user_repository_ = std::make_unique<UserRepository>(repository_config, mysql_pool_, redis_pool_, thread_pool_);

                LOG_INFO("业务组件初始化完成");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("初始化业务组件时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 检查端口可用性
         * @param host 主机地址
         * @param port 端口号
         * @return 端口可用返回true
         */
        bool AuthService::checkPortAvailability(const std::string& host, int port) {
            try {
                LOG_DEBUG("检查端口可用性: " + host + ":" + std::to_string(port));

                // 创建测试socket
                int test_socket = ::socket(AF_INET, SOCK_STREAM, 0);
                if (test_socket < 0) {
                    LOG_ERROR("创建测试socket失败: " + std::string(strerror(errno)));
                    return false;
                }

                // 设置与实际服务器相同的socket选项
                int reuse_addr = 1;
                if (::setsockopt(test_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0) {
                    LOG_WARNING("设置SO_REUSEADDR失败: " + std::string(strerror(errno)));
                }

                // 设置SO_REUSEPORT（如果支持）
                int reuse_port = 1;
                if (::setsockopt(test_socket, SOL_SOCKET, SO_REUSEPORT, &reuse_port, sizeof(reuse_port)) < 0) {
                    // SO_REUSEPORT失败不是致命错误
                    LOG_DEBUG("SO_REUSEPORT不支持或设置失败: " + std::string(strerror(errno)));
                }

                // 创建地址结构
                struct sockaddr_in addr;
                std::memset(&addr, 0, sizeof(addr));
                addr.sin_family = AF_INET;
                addr.sin_port = htons(port);

                if (host == "0.0.0.0" || host.empty()) {
                    addr.sin_addr.s_addr = INADDR_ANY;
                } else {
                    if (::inet_pton(AF_INET, host.c_str(), &addr.sin_addr) <= 0) {
                        LOG_ERROR("无效的IP地址: " + host);
                        ::close(test_socket);
                        return false;
                    }
                }

                // 尝试绑定
                bool available = true;
                if (::bind(test_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
                    int error = errno;
                    if (error == EADDRINUSE) {
                        // 即使端口被占用，如果我们设置了SO_REUSEADDR，也可能可以重用
                        LOG_DEBUG("端口被占用，但由于SO_REUSEADDR设置，可能仍可使用: " + host + ":" + std::to_string(port));
                        available = true;  // 允许继续，让实际的bind操作来决定
                    } else {
                        LOG_ERROR("绑定测试失败: " + std::string(strerror(error)));
                        available = false;
                    }
                } else {
                    LOG_DEBUG("端口完全可用: " + host + ":" + std::to_string(port));
                }

                // 关闭测试socket
                ::close(test_socket);
                return available;

            } catch (const std::exception& e) {
                LOG_ERROR("检查端口可用性时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 初始化HTTP服务器
         * @return 初始化成功返回true
         */
        bool AuthService::initializeHttpServer() {
            try {
                // 检查端口是否可用（仅作为信息提示，不阻止启动）
                if (!checkPortAvailability(config_.host, config_.port)) {
                    LOG_WARNING("端口检查显示端口可能被占用，但由于SO_REUSEADDR设置，仍尝试启动: " +
                               config_.host + ":" + std::to_string(config_.port));
                }

                // 创建HTTP服务器配置（与API Gateway保持一致）
                common::http::HttpServerConfig http_config;

                // 基础网络配置（与API Gateway相同）
                http_config.host = config_.host;
                http_config.port = config_.port;
                http_config.backlog = 1024;
                http_config.reuse_addr = true;               // 启用地址重用（与API Gateway一致）
                http_config.reuse_port = false;              // 禁用端口重用

                // HTTP协议配置（与API Gateway相同）
                http_config.max_request_size = 1048576;      // 1MB
                http_config.max_header_size = 8192;          // 8KB
                http_config.request_timeout_ms = 30000;      // 30秒
                http_config.keep_alive_timeout_ms = 60000;   // 60秒
                http_config.max_keep_alive_requests = 100;

                // 线程池配置
                http_config.worker_threads = config_.worker_threads;
                http_config.io_threads = 1;
                http_config.enable_thread_pool = true;

                // 性能优化配置
                http_config.enable_tcp_nodelay = true;
                http_config.enable_so_reuseaddr = true;
                http_config.send_buffer_size = 65536;        // 64KB
                http_config.recv_buffer_size = 65536;        // 64KB

                // 安全配置
                http_config.enable_cors = true;
                http_config.cors_origin = "*";

                // 日志和监控配置
                http_config.enable_access_log = true;
                http_config.enable_error_log = true;
                http_config.enable_performance_monitoring = true;
                http_config.stats_interval_ms = 5000;

                LOG_INFO("HTTP服务器配置详情:");
                LOG_INFO("  - 监听地址: " + http_config.host + ":" + std::to_string(http_config.port));
                LOG_INFO("  - 工作线程: " + std::to_string(http_config.worker_threads));
                LOG_INFO("  - 地址重用: " + std::string(http_config.reuse_addr ? "启用" : "禁用"));
                LOG_INFO("  - TCP_NODELAY: " + std::string(http_config.enable_tcp_nodelay ? "启用" : "禁用"));
                LOG_INFO("  - 请求超时: " + std::to_string(http_config.request_timeout_ms) + "ms");
                LOG_INFO("  - Keep-Alive超时: " + std::to_string(http_config.keep_alive_timeout_ms) + "ms");

                http_server_ = std::make_unique<common::http::HttpServer>(http_config);

                // 注册HTTP路由
                registerHttpRoutes();

                LOG_INFO("HTTP服务器初始化完成");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("初始化HTTP服务器时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 初始化Kafka组件
         * @return 初始化成功返回true
         */
        bool AuthService::initializeKafka() {
            try {
                // 初始化Kafka生产者配置
                common::messaging::KafkaProducerConfig producer_config;
                producer_config.brokers = config_.kafka_brokers;
                producer_config.clientId = config_.service_name + "_producer";
                producer_config.timeoutMs = 5000;
                producer_config.queueBufferingMaxMs = 1000;
                producer_config.queueBufferingMaxMessages = 100000;
                producer_config.requestRequiredAcks = 1;

                kafka_producer_ = common::messaging::KafkaProducer::create(producer_config);

                // 初始化Kafka消费者配置
                common::messaging::KafkaConsumerConfig consumer_config;
                consumer_config.brokers = config_.kafka_brokers;
                consumer_config.groupId = config_.service_name + "_group";
                consumer_config.clientId = config_.service_name + "_consumer";
                consumer_config.sessionTimeoutMs = 30000;
                consumer_config.maxPollIntervalMs = 300000;
                consumer_config.offsetReset = "latest";
                consumer_config.fetchMaxBytes = 1048576;
                consumer_config.fetchMaxWaitMs = 500;

                kafka_consumer_ = common::messaging::KafkaConsumer::create(consumer_config);

                // Kafka消费者通常不需要显式初始化，在订阅时会自动连接

                LOG_INFO("Kafka组件初始化完成");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("初始化Kafka组件时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 构建错误响应
         * @param error_code 错误代码
         * @param error_message 错误消息
         * @return 错误响应JSON
         */
        nlohmann::json AuthService::buildErrorResponse(const std::string& error_code, const std::string& error_message) {
            return {
                {"success", false},
                {"error", {
                    {"code", error_code},
                    {"message", error_message}
                }},
                {"timestamp", getCurrentTimestamp()},
                {"service", config_.service_name}
            };
        }

        /**
         * @brief 构建成功响应
         * @param data 响应数据
         * @return 成功响应JSON
         */
        nlohmann::json AuthService::buildSuccessResponse(const nlohmann::json& data) {
            return {
                {"success", true},
                {"data", data},
                {"timestamp", getCurrentTimestamp()},
                {"service", config_.service_name}
            };
        }

        /**
         * @brief 记录请求日志
         * @param endpoint 端点
         * @param method 方法
         * @param client_ip 客户端IP
         * @param user_id 用户ID
         * @param response_code 响应代码
         * @param response_time 响应时间
         */
        void AuthService::logRequest(const std::string& endpoint, const std::string& method, const std::string& client_ip,
                                    int64_t user_id, int response_code, std::chrono::milliseconds response_time) {
            if (!config_.enable_request_logging) {
                return;
            }

            try {
                nlohmann::json log_entry = {
                    {"timestamp", getCurrentTimestamp()},
                    {"service", config_.service_name},
                    {"endpoint", endpoint},
                    {"method", method},
                    {"client_ip", client_ip},
                    {"user_id", user_id},
                    {"response_code", response_code},
                    {"response_time_ms", response_time.count()}
                };

                LOG_DEBUG("API请求: " + log_entry.dump());

            } catch (const std::exception& e) {
                LOG_ERROR("记录请求日志时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 获取健康检查信息
         * @return 健康检查结果
         */
        nlohmann::json AuthService::getHealthCheck() const {
            nlohmann::json health = {
                {"service", config_.service_name},
                {"version", config_.service_version},
                {"status", "healthy"},
                {"timestamp", getCurrentTimestamp()},
                {"uptime_seconds", std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::system_clock::now() - std::chrono::system_clock::from_time_t(0)).count()},
                {"checks", nlohmann::json::object()}
            };

            // 检查数据库连接
            health["checks"]["mysql"] = nlohmann::json{
                {"status", mysql_pool_ && mysql_pool_->isRunning() ? "healthy" : "unhealthy"},
                {"pool_size", mysql_pool_ ? mysql_pool_->getTotalConnections() : 0},
                {"active_connections", mysql_pool_ ? mysql_pool_->getActiveConnections() : 0}
            };

            health["checks"]["redis"] = nlohmann::json{
                {"status", redis_pool_ && redis_pool_->isRunning() ? "healthy" : "unhealthy"},
                {"pool_size", redis_pool_ ? redis_pool_->getTotalConnections() : 0},
                {"active_connections", redis_pool_ ? redis_pool_->getActiveConnections() : 0}
            };

            // 检查Kafka连接
            if (config_.enable_kafka) {
                health["checks"]["kafka"] = nlohmann::json{
                    {"producer_status", kafka_producer_ ? "initialized" : "not_initialized"},
                    {"consumer_status", kafka_consumer_ ? "initialized" : "not_initialized"}
                };
            }

            // 检查组件状态
            health["checks"]["components"] = {
                {"jwt_manager", jwt_manager_ ? "initialized" : "not_initialized"},
                {"password_manager", password_manager_ ? "initialized" : "not_initialized"},
                {"session_manager", session_manager_ ? "initialized" : "not_initialized"},
                {"user_repository", user_repository_ ? "initialized" : "not_initialized"}
            };

            return health;
        }

        /**
         * @brief 获取服务统计信息
         * @return 统计信息
         */
        nlohmann::json AuthService::getServiceStatistics() const {
            nlohmann::json stats = {
                {"service", config_.service_name},
                {"version", config_.service_version},
                {"timestamp", getCurrentTimestamp()},
                {"requests", {
                    {"total", total_requests_.load()},
                    {"successful", successful_requests_.load()},
                    {"failed", failed_requests_.load()},
                    {"success_rate", total_requests_.load() > 0 ?
                        static_cast<double>(successful_requests_.load()) / total_requests_.load() : 0.0}
                }},
                {"auth", {
                    {"registrations", registrations_.load()},
                    {"logins", logins_.load()},
                    {"game_logins", game_logins_.load()}
                }}
            };

            // 添加组件统计信息
            if (jwt_manager_) {
                stats["jwt"] = jwt_manager_->getStatistics();
            }

            if (password_manager_) {
                stats["password"] = password_manager_->getStatistics();
            }

            if (session_manager_) {
                stats["session"] = session_manager_->getStatistics();
            }

            if (user_repository_) {
                stats["repository"] = user_repository_->getStatistics();
            }

            return stats;
        }

        /**
         * @brief 更新游戏服务器缓存
         * @return 更新成功返回true
         */
        bool AuthService::updateGameServersCache() {
            try {
                // 这里应该从数据库或服务发现系统获取游戏服务器列表
                // 为了演示，我们创建一些示例服务器

                std::unique_lock<std::shared_mutex> lock(game_servers_mutex_);

                // 清空现有缓存
                game_servers_cache_.clear();

                // 添加示例游戏服务器
                // 创建贪吃蛇服务器列表
                std::vector<GameServerInfo> snake_servers;
                GameServerInfo snake1("snake_server_01", "snake1.game.com", 9001, GameType::SNAKE);
                snake1.server_name = "贪吃蛇服务器01";
                snake_servers.push_back(snake1);

                GameServerInfo snake2("snake_server_02", "snake2.game.com", 9002, GameType::SNAKE);
                snake2.server_name = "贪吃蛇服务器02";
                snake_servers.push_back(snake2);

                // 创建俄罗斯方块服务器列表
                std::vector<GameServerInfo> tetris_servers;
                GameServerInfo tetris1("tetris_server_01", "tetris1.game.com", 9011, GameType::TETRIS);
                tetris1.server_name = "俄罗斯方块服务器01";
                tetris_servers.push_back(tetris1);

                GameServerInfo tetris2("tetris_server_02", "tetris2.game.com", 9012, GameType::TETRIS);
                tetris2.server_name = "俄罗斯方块服务器02";
                tetris_servers.push_back(tetris2);

                game_servers_cache_[GameType::SNAKE] = snake_servers;
                game_servers_cache_[GameType::TETRIS] = tetris_servers;

                last_server_update_ = std::chrono::system_clock::now();

                LOG_INFO("游戏服务器缓存更新完成");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("更新游戏服务器缓存时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 用户登出
         * @param access_token 访问令牌
         * @return 登出成功返回true
         */
        bool AuthService::logoutUser(const std::string& access_token) {
            try {
                // 1. 验证访问令牌
                auto token_validation = jwt_manager_->validateAccessToken(access_token);
                if (!token_validation.valid) {
                    LOG_WARNING("登出时令牌验证失败: " + token_validation.error_message);
                    return false;
                }

                auto user_claims = token_validation.claims.value();

                // 2. 销毁会话
                if (!user_claims.session_id.empty()) {
                    session_manager_->destroySession(user_claims.session_id);
                }

                // 3. 将令牌加入黑名单
                jwt_manager_->revokeToken(access_token);

                // 4. 更新用户在线状态
                auto user_opt = user_repository_->findUserById(user_claims.user_id, false);
                if (user_opt.has_value()) {
                    auto user_info = user_opt.value();
                    user_info.online_status = OnlineStatus::OFFLINE;
                    user_info.updated_at = std::chrono::system_clock::now();
                    user_repository_->updateUser(user_info);
                }

                // 5. 发布用户登出事件
                publishUserEvent("user_logged_out", user_claims.user_id, {
                    {"logout_time", getCurrentTimestamp()},
                    {"session_id", user_claims.session_id}
                });

                LOG_INFO("用户登出成功，用户ID: " + std::to_string(user_claims.user_id));
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("用户登出时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 刷新访问令牌
         * @param refresh_token 刷新令牌
         * @return 认证结果
         */
        AuthResult AuthService::refreshToken(const std::string& refresh_token) {
            try {
                total_requests_++;

                // 1. 验证刷新令牌
                auto token_validation = jwt_manager_->validateRefreshToken(refresh_token);
                if (!token_validation.valid) {
                    failed_requests_++;
                    return AuthResult("刷新令牌验证失败: " + token_validation.error_message, "INVALID_REFRESH_TOKEN");
                }

                auto user_claims = token_validation.claims.value();

                // 2. 获取用户信息
                auto user_opt = user_repository_->findUserById(user_claims.user_id);
                if (!user_opt.has_value()) {
                    failed_requests_++;
                    return AuthResult("用户不存在", "USER_NOT_FOUND");
                }

                auto user_info = user_opt.value();

                // 3. 检查用户状态
                if (user_info.status != UserStatus::ACTIVE) {
                    failed_requests_++;
                    return AuthResult("用户状态异常", "USER_STATUS_INVALID");
                }

                // 4. 获取会话信息
                auto session_opt = session_manager_->getSession(user_claims.session_id);
                if (!session_opt.has_value()) {
                    failed_requests_++;
                    return AuthResult("会话不存在", "SESSION_NOT_FOUND");
                }

                auto session = session_opt.value();

                // 5. 生成新的访问令牌
                std::string new_access_token = jwt_manager_->generateAccessToken(user_info, session.session_id, session.device_type, session.client_ip);

                // 6. 撤销旧的刷新令牌并生成新的
                jwt_manager_->revokeToken(refresh_token);
                std::string new_refresh_token = jwt_manager_->generateRefreshToken(user_info, session.session_id, session.device_type, session.client_ip);

                successful_requests_++;
                LOG_INFO("令牌刷新成功，用户ID: " + std::to_string(user_info.user_id));

                return AuthResult(user_info, session, new_access_token, new_refresh_token);

            } catch (const std::exception& e) {
                failed_requests_++;
                LOG_ERROR("刷新令牌时发生异常: " + std::string(e.what()));
                return AuthResult("服务器内部错误", "INTERNAL_ERROR");
            }
        }

        /**
         * @brief 验证访问令牌
         * @param access_token 访问令牌
         * @param client_ip 客户端IP
         * @return 令牌验证结果
         */
        TokenValidationResult AuthService::validateToken(const std::string& access_token, const std::string& client_ip) {
            try {
                total_requests_++;

                // 1. 验证JWT令牌
                auto token_validation = jwt_manager_->validateAccessToken(access_token);
                if (!token_validation.valid) {
                    failed_requests_++;
                    return TokenValidationResult("令牌验证失败: " + token_validation.error_message, "INVALID_TOKEN");
                }

                auto user_claims = token_validation.claims.value();

                // 2. 验证会话
                auto session_validation = session_manager_->validateSession(user_claims.session_id, client_ip);
                if (!session_validation.valid) {
                    failed_requests_++;
                    return TokenValidationResult("会话验证失败: " + session_validation.error_message, "INVALID_SESSION");
                }

                // 3. 获取用户信息
                auto user_opt = user_repository_->findUserById(user_claims.user_id);
                if (!user_opt.has_value()) {
                    failed_requests_++;
                    return TokenValidationResult("用户不存在", "USER_NOT_FOUND");
                }

                auto user_info = user_opt.value();

                // 4. 检查用户状态
                if (user_info.status != UserStatus::ACTIVE) {
                    failed_requests_++;
                    return TokenValidationResult("用户状态异常", "USER_STATUS_INVALID");
                }

                successful_requests_++;
                TokenValidationResult result(user_claims);
                return result;

            } catch (const std::exception& e) {
                failed_requests_++;
                LOG_ERROR("验证访问令牌时发生异常: " + std::string(e.what()));
                return TokenValidationResult("服务器内部错误", "INTERNAL_ERROR");
            }
        }

        /**
         * @brief 获取游戏服务器列表
         * @param game_type 游戏类型
         * @param region 区域（可选）
         * @return 游戏服务器信息列表
         */
        std::vector<GameServerInfo> AuthService::getGameServers(GameType game_type, const std::string& region) {
            try {
                std::shared_lock<std::shared_mutex> lock(game_servers_mutex_);

                auto it = game_servers_cache_.find(game_type);
                if (it == game_servers_cache_.end()) {
                    return {};
                }

                auto& servers = it->second;

                // 如果指定了区域，过滤服务器
                if (!region.empty()) {
                    std::vector<GameServerInfo> filtered_servers;
                    for (const auto& server : servers) {
                        if (server.metadata.find("region") != server.metadata.end() &&
                            server.metadata.at("region") == region) {
                            filtered_servers.push_back(server);
                        }
                    }
                    return filtered_servers;
                }

                return servers;

            } catch (const std::exception& e) {
                LOG_ERROR("获取游戏服务器列表时发生异常: " + std::string(e.what()));
                return {};
            }
        }

        /**
         * @brief 获取服务状态
         * @return 服务状态信息
         */
        nlohmann::json AuthService::getServiceStatus() const {
            nlohmann::json status;

            status["service"] = config_.service_name;
            status["version"] = config_.service_version;
            status["status"] = running_ ? "running" : "stopped";
            status["initialized"] = initialized_.load();
            status["timestamp"] = getCurrentTimestamp();

            // 组件状态
            status["components"] = {
                {"http_server", http_server_ ? "initialized" : "not_initialized"},
                {"mysql_pool", mysql_pool_ ? "initialized" : "not_initialized"},
                {"redis_pool", redis_pool_ ? "initialized" : "not_initialized"},
                {"kafka_producer", kafka_producer_ ? "initialized" : "not_initialized"},
                {"kafka_consumer", kafka_consumer_ ? "initialized" : "not_initialized"},
                {"jwt_manager", jwt_manager_ ? "initialized" : "not_initialized"},
                {"password_manager", password_manager_ ? "initialized" : "not_initialized"},
                {"session_manager", session_manager_ ? "initialized" : "not_initialized"},
                {"user_repository", user_repository_ ? "initialized" : "not_initialized"}
            };

            // 配置信息
            status["config"] = {
                {"host", config_.host},
                {"port", config_.port},
                {"worker_threads", config_.worker_threads},
                {"enable_https", config_.enable_https},
                {"enable_kafka", config_.enable_kafka},
                {"enable_service_discovery", config_.enable_service_discovery}
            };

            return status;
        }

        /**
         * @brief 启动定时任务
         */
        void AuthService::startScheduledTasks() {
            if (!scheduler_) {
                return;
            }

            // 启动游戏服务器缓存更新任务
            scheduler_->scheduleEvery(std::chrono::minutes(5), [this]() {
                this->updateGameServersCache();
            });

            // 启动统计信息重置任务 (每24小时执行一次)
            scheduler_->scheduleEvery(std::chrono::hours(24), [this]() {
                this->resetStatistics();
            });

            LOG_INFO("定时任务启动完成");
        }

        /**
         * @brief 启动心跳任务
         */
        void AuthService::startHeartbeatTask() {
            if (!scheduler_) {
                LOG_ERROR("调度器未初始化，无法启动心跳任务");
                return;
            }

            LOG_INFO("启动心跳任务，间隔: " + std::to_string(config_.heartbeat_interval.count()) + "秒");
            LOG_INFO("目标API Gateway: " + config_.api_gateway_host + ":" + std::to_string(config_.api_gateway_port));
            LOG_INFO("调度器状态: " + std::string(scheduler_->isRunning() ? "运行中" : "未运行"));
            LOG_INFO("调度器待执行任务数: " + std::to_string(scheduler_->getPendingTaskCount()));

            scheduler_->scheduleEvery(config_.heartbeat_interval, [this]() {
                LOG_INFO("执行心跳任务...");
                // 发送心跳到API Gateway
                try {
                    std::string gateway_url = "http://" + config_.api_gateway_host + ":" +
                                            std::to_string(config_.api_gateway_port) + "/api/v1/services/heartbeat";

                    // 确定心跳地址：与注册时保持一致
                    std::string heartbeat_host = config_.host;
                    if (heartbeat_host == "0.0.0.0" || heartbeat_host.empty()) {
                        heartbeat_host = "127.0.0.1";  // 与注册时保持一致
                    }

                    nlohmann::json heartbeat = {
                        {"service_name", config_.service_name},
                        {"host", heartbeat_host},
                        {"port", config_.port}
                    };

                    common::http::HttpClient http_client;
                    std::unordered_map<std::string, std::string> headers = {
                        {"Content-Type", "application/json"}
                    };

                    auto response = http_client.post(gateway_url, heartbeat.dump(), headers, 3000);

                    if (response.status_code >= 200 && response.status_code < 300) {
                        LOG_INFO("心跳发送成功到API Gateway: " + gateway_url);
                    } else {
                        LOG_WARNING("心跳发送失败，状态码: " + std::to_string(response.status_code) +
                                   ", 响应: " + response.body + ", URL: " + gateway_url);
                    }
                } catch (const std::exception& e) {
                    LOG_ERROR("发送心跳异常: " + std::string(e.what()));
                }
            });

            LOG_INFO("心跳任务启动完成");
            LOG_INFO("心跳任务添加后，调度器待执行任务数: " + std::to_string(scheduler_->getPendingTaskCount()));
        }

        /**
         * @brief 注册到API Gateway
         * @return 注册成功返回true
         */
        bool AuthService::registerToApiGateway() {
            try {
                // 确定注册地址：如果监听0.0.0.0，则注册为127.0.0.1
                std::string register_host = config_.host;
                if (register_host == "0.0.0.0" || register_host.empty()) {
                    register_host = "127.0.0.1";  // 网关可以访问的地址
                }

                // 构建服务注册信息
                nlohmann::json registration = {
                    {"service_name", config_.service_name},
                    {"service_version", config_.service_version},
                    {"host", register_host},
                    {"port", config_.port},
                    {"health_check_endpoint", "/health"},
                    {"endpoints", nlohmann::json::array({
                        "/api/v1/auth/register",
                        "/api/v1/auth/login",
                        "/api/v1/auth/logout",
                        "/api/v1/auth/refresh",
                        "/api/v1/auth/validate",
                        "/api/v1/game/login",
                        "/api/v1/game/servers"
                    })}
                };

                LOG_INFO("注册服务地址: " + register_host + ":" + std::to_string(config_.port));

                // 实现向API Gateway发送注册请求的逻辑
                std::string gateway_url = "http://" + config_.api_gateway_host + ":" +
                                        std::to_string(config_.api_gateway_port) + "/api/v1/services/register";

                // 创建HTTP客户端
                common::http::HttpClient http_client;

                // 设置请求头
                std::unordered_map<std::string, std::string> headers = {
                    {"Content-Type", "application/json"},
                    {"User-Agent", "AuthService/1.0.0"}
                };

                // 发送注册请求
                auto response = http_client.post(gateway_url, registration.dump(), headers, 5000);

                if (response.status_code >= 200 && response.status_code < 300) {
                    LOG_INFO("服务注册到API Gateway成功: " + gateway_url);
                    return true;
                } else {
                    LOG_ERROR("服务注册到API Gateway失败，状态码: " + std::to_string(response.status_code) +
                             ", 响应: " + response.body +
                             ", 错误信息: " + response.error_message);
                    return false;
                }

            } catch (const std::exception& e) {
                LOG_ERROR("注册到API Gateway时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 重置统计信息
         */
        void AuthService::resetStatistics() {
            total_requests_ = 0;
            successful_requests_ = 0;
            failed_requests_ = 0;
            registrations_ = 0;
            logins_ = 0;
            game_logins_ = 0;

            // 重置组件统计信息
            if (jwt_manager_) {
                jwt_manager_->resetStatistics();
            }
            if (password_manager_) {
                password_manager_->resetStatistics();
            }
            if (session_manager_) {
                session_manager_->resetStatistics();
            }
            if (user_repository_) {
                user_repository_->resetStatistics();
            }

            LOG_INFO("统计信息已重置");
        }

        /**
         * @brief 强制清理用户会话（管理员操作）
         * @param user_id 用户ID
         * @param reason 清理原因
         * @return 清理的会话数量
         */
        int AuthService::forceCleanupUserSessions(int64_t user_id, const std::string& reason) {
            try {
                if (!session_manager_) {
                    return 0;
                }

                int cleaned_count = session_manager_->forceCleanupUserSessions(user_id, reason);

                // 记录管理员操作日志
                LOG_WARNING("管理员强制清理用户会话: 用户ID=" + std::to_string(user_id) +
                           ", 原因=" + reason + ", 清理数量=" + std::to_string(cleaned_count));

                return cleaned_count;

            } catch (const std::exception& e) {
                LOG_ERROR("强制清理用户会话失败: " + std::string(e.what()));
                return 0;
            }
        }

        /**
         * @brief 验证请求权限
         * @param access_token 访问令牌
         * @param required_roles 需要的角色
         * @return 验证通过返回true
         */
        bool AuthService::validateRequestPermission(const std::string& access_token, const std::vector<std::string>& required_roles) {
            try {
                // 验证令牌
                auto validation_result = validateToken(access_token);
                if (!validation_result.valid) {
                    return false;
                }

                // 如果不需要特定角色，令牌有效即可
                if (required_roles.empty()) {
                    return true;
                }

                // 检查用户角色
                if (!validation_result.claims.has_value()) {
                    return false;
                }
                auto user = user_repository_->findUserById(validation_result.claims->user_id, true);
                if (!user.has_value()) {
                    return false;
                }

                // 检查是否有所需角色
                for (const auto& required_role : required_roles) {
                    bool has_role = false;
                    for (const auto& user_role : user.value().roles) {
                        if (user_role == required_role) {
                            has_role = true;
                            break;
                        }
                    }
                    if (!has_role) {
                        return false;
                    }
                }

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("验证请求权限失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 处理游戏服务器注册事件
         * @param server_info 服务器信息
         */
        void AuthService::handleGameServerRegistered(const GameServerInfo& server_info) {
            try {
                LOG_INFO("游戏服务器注册: " + server_info.server_id + " (" + server_info.server_name + ")");

                // 更新游戏服务器缓存
                updateGameServersCache();

                // 记录服务器注册事件
                nlohmann::json event_data = {
                    {"event_type", "server_registered"},
                    {"server_info", server_info.toJson()},
                    {"timestamp", getCurrentTimestamp()}
                };

                // 可以在这里添加更多的业务逻辑，比如通知其他服务

            } catch (const std::exception& e) {
                LOG_ERROR("处理游戏服务器注册事件失败: " + std::string(e.what()));
            }
        }

        /**
         * @brief 处理游戏服务器注销事件
         * @param server_id 服务器ID
         */
        void AuthService::handleGameServerUnregistered(const std::string& server_id) {
            try {
                LOG_INFO("游戏服务器注销: " + server_id);

                // 更新游戏服务器缓存
                updateGameServersCache();

                // 记录服务器注销事件
                nlohmann::json event_data = {
                    {"event_type", "server_unregistered"},
                    {"server_id", server_id},
                    {"timestamp", getCurrentTimestamp()}
                };

                // 可以在这里添加更多的业务逻辑，比如迁移用户会话

            } catch (const std::exception& e) {
                LOG_ERROR("处理游戏服务器注销事件失败: " + std::string(e.what()));
            }
        }

        /**
         * @brief 处理用户封禁事件
         * @param user_id 用户ID
         */
        void AuthService::handleUserBanned(int64_t user_id) {
            try {
                LOG_INFO("用户封禁: " + std::to_string(user_id));

                // 强制登出用户的所有会话
                if (session_manager_) {
                    session_manager_->forceCleanupUserSessions(user_id, "用户被封禁");
                }

                // 将用户的所有令牌加入黑名单
                if (jwt_manager_) {
                    // 这里可以添加将用户所有令牌加入黑名单的逻辑
                }

                // 记录封禁事件
                nlohmann::json event_data = {
                    {"event_type", "user_banned"},
                    {"user_id", user_id},
                    {"timestamp", getCurrentTimestamp()}
                };

            } catch (const std::exception& e) {
                LOG_ERROR("处理用户封禁事件失败: " + std::string(e.what()));
            }
        }

        /**
         * @brief 处理用户解封事件
         * @param user_id 用户ID
         */
        void AuthService::handleUserUnbanned(int64_t user_id) {
            try {
                LOG_INFO("用户解封: " + std::to_string(user_id));

                // 记录解封事件
                nlohmann::json event_data = {
                    {"event_type", "user_unbanned"},
                    {"user_id", user_id},
                    {"timestamp", getCurrentTimestamp()}
                };

                // 可以在这里添加更多的业务逻辑，比如通知用户

            } catch (const std::exception& e) {
                LOG_ERROR("处理用户解封事件失败: " + std::string(e.what()));
            }
        }

        /**
         * @brief 处理强制登出事件
         * @param user_id 用户ID
         */
        void AuthService::handleForceLogout(int64_t user_id) {
            try {
                LOG_INFO("强制登出用户: " + std::to_string(user_id));

                // 强制登出用户的所有会话
                if (session_manager_) {
                    session_manager_->forceCleanupUserSessions(user_id, "管理员强制登出");
                }

                // 记录强制登出事件
                nlohmann::json event_data = {
                    {"event_type", "force_logout"},
                    {"user_id", user_id},
                    {"timestamp", getCurrentTimestamp()}
                };

            } catch (const std::exception& e) {
                LOG_ERROR("处理强制登出事件失败: " + std::string(e.what()));
            }
        }

        /**
         * @brief 处理清除缓存事件
         * @param cache_type 缓存类型
         */
        void AuthService::handleClearCache(const std::string& cache_type) {
            try {
                LOG_INFO("清除缓存: " + cache_type);

                if (cache_type == "all" || cache_type == "user") {
                    if (user_repository_) {
                        user_repository_->clearAllCache();
                    }
                }

                if (cache_type == "all" || cache_type == "session") {
                    if (session_manager_) {
                        // 这里可以添加清除会话缓存的逻辑
                    }
                }

                if (cache_type == "all" || cache_type == "jwt") {
                    if (jwt_manager_) {
                        // 这里可以添加清除JWT缓存的逻辑
                    }
                }

                // 记录缓存清除事件
                nlohmann::json event_data = {
                    {"event_type", "cache_cleared"},
                    {"cache_type", cache_type},
                    {"timestamp", getCurrentTimestamp()}
                };

            } catch (const std::exception& e) {
                LOG_ERROR("处理清除缓存事件失败: " + std::string(e.what()));
            }
        }

        /**
         * @brief 重启服务
         */
        bool AuthService::restart() {
            try {
                LOG_INFO("开始重启AuthService...");

                // 停止服务
                stop();

                // 等待一段时间确保资源释放
                std::this_thread::sleep_for(std::chrono::seconds(2));

                // 重新启动服务
                if (start()) {
                    LOG_INFO("AuthService重启成功");
                    return true;
                } else {
                    LOG_ERROR("AuthService重启失败");
                    return false;
                }

            } catch (const std::exception& e) {
                LOG_ERROR("重启AuthService失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 启动连接池监控
         */
        void AuthService::startConnectionPoolMonitoring() {
            if (!mysql_pool_) {
                LOG_WARNING("MySQL连接池未初始化，跳过连接池监控");
                return;
            }

            // 检查监控线程是否已经在运行
            if (connection_pool_monitor_thread_.joinable()) {
                LOG_WARNING("连接池监控线程已在运行，跳过重复启动");
                return;
            }

            LOG_INFO("启动连接池监控线程...");

            // 启动监控线程
            connection_pool_monitor_thread_ = std::thread([this]() {
                LOG_INFO("连接池监控线程启动");

                // 使用独立的运行标志，避免依赖主服务的running_状态
                bool monitor_running = true;

                while (monitor_running && mysql_pool_ && mysql_pool_->isRunning()) {
                    try {
                        // 每30秒检查一次连接池状态
                        std::this_thread::sleep_for(std::chrono::seconds(30));

                        // 检查服务是否仍在运行
                        if (!running_.load()) {
                            monitor_running = false;
                            break;
                        }

                        // 检查连接池是否仍然有效
                        if (!mysql_pool_ || !mysql_pool_->isRunning()) {
                            LOG_WARNING("MySQL连接池已停止，退出监控");
                            break;
                        }

                        // 获取连接池统计信息
                        size_t active_connections = mysql_pool_->getActiveConnections();
                        size_t idle_connections = mysql_pool_->getIdleConnections();
                        size_t total_connections = mysql_pool_->getTotalConnections();

                        // 记录连接池状态
                        LOG_DEBUG("连接池状态监控 - 活跃: " + std::to_string(active_connections) +
                                ", 空闲: " + std::to_string(idle_connections) +
                                ", 总计: " + std::to_string(total_connections) +
                                ", 最大: " + std::to_string(config_.mysql_pool_size));

                        // 检查连接池是否接近满载
                        double usage_ratio = static_cast<double>(active_connections) / static_cast<double>(config_.mysql_pool_size);
                        if (usage_ratio > 0.8) {
                            LOG_WARNING("连接池使用率过高: " + std::to_string(usage_ratio * 100) + "%");
                        }

                        // 检查是否有空闲连接
                        if (idle_connections == 0 && active_connections >= static_cast<size_t>(config_.mysql_pool_size)) {
                            LOG_WARNING("连接池已满，可能影响性能");
                        }

                    } catch (const std::exception& e) {
                        LOG_ERROR("连接池监控异常: " + std::string(e.what()));
                        // 发生异常时等待一段时间再继续，避免快速循环
                        std::this_thread::sleep_for(std::chrono::seconds(5));
                    } catch (...) {
                        LOG_ERROR("连接池监控发生未知异常");
                        // 发生未知异常时等待一段时间再继续
                        std::this_thread::sleep_for(std::chrono::seconds(5));
                    }
                }

                LOG_INFO("连接池监控线程退出");
            });

            LOG_INFO("连接池监控启动完成");
        }

    } // namespace auth_service
} // namespace core_services
